###############################################################################
# SNOW.R
#
# Distributes simulations to different CPUs
#
# Last edited: 16 Feb 2016 by Roni 
###############################################################################

#########################
## ESTIMATION STRATEGY ##
#########################
##  Rule              Number      Burn-in     run-time     number of runs     type of average
## Sticker              4           75          1             500               ensemble
## Governator           3           75          1             500               ensemble
## Hunting Governator   8           75          1             500               ensemble
## Hunter               7          100         500             1                time
## Aggregator           2           75          1             500               ensemble


rm(list = ls(all = TRUE))
library(data.table)
library(plyr)
set.seed(539139152)

################################
# GET THE INPUT MATRIX AS LIST #
################################

repeat.single.row <- function(x, rep.vector) {
matrix(kronecker(as.matrix(x), rep(1, rep.vector)), nrow=rep.vector)
}

repeat.rows <- function(x, rep.vector) {
   x.list <- alply(x, 1, NULL)
    output <- do.call(rbind, mapply(repeat.single.row, x.list, rep.vector, SIMPLIFY=FALSE))
    return(output)
}

## # set number of simulations, runs, voters and parties
N <- 35000

input <- data.frame(parties=sample(2:8, N, TRUE),
                   discount=runif(N, 0, 1),
                   memory=sample(2:10, N, TRUE), 
                   aspiration=runif(N, 0, .9),
                   alpha=runif(N, 0, 1),
                   sd.distance=runif(N, 0, 2)
                  )
Nruns <- 500
input$experiment <- seq_len(nrow(input))
input$no.evo.length <- 75
input$evo.burn.in <- 1000 
input <- repeat.rows(input, Nruns)
input <- as.data.frame(cbind(input, sample(seq_len(99999999), nrow(input), FALSE)))
names(input) <- c("parties", "discount", "memory", "aspiration","alpha","sd.distance", 
                  "experiment",  "no.evo.length", "evo.burn.in", "seed")
input$num <- rep(seq_len(Nruns), length(unique(input$experiment)))


#with many levels, loop seems to be faster than split
input <- as.data.table(input)
setkey(input, experiment)
input.list <- list()
for (i in 1:N) {
 print(i)
 input.list[[i]] <- input[experiment==i]
}

save(input.list, file="input.list.Rdata")
